﻿#region Usings

using System;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.XPath;
using Yandex.Market.Api.YmlSerialization;

#endregion

namespace Yandex.Market.Api.Model
{
    /// <summary>
    /// </summary>
    [YmlSerializeAs("yml_catalog")]
    [Serializable]
    public class YmlCatalog : ICloneable
    {
        /// <summary>
        ///   Должен соответствовать дате и времени генерации XML-файла на стороне магазина.
        ///   Дата должна иметь формат YYYY-MM-DD hh:mm
        /// </summary>
        [YmlFormat("yyyy-MM-dd HH:mm")]
        [YmlSerializeAs("date")]
        [YmlAttributeForClass]
        public DateTime Date { get; set; }

        /// <summary>
        ///   Cодержит описание магазина и его товарных предложений.
        /// </summary>
        [YmlSerializeAs("shop")]
        public Shop Shop { set; get; }

        #region Implementation of ICloneable

        /// <summary>
        ///   Creates a new object that is a copy of the current instance.
        /// </summary>
        /// <returns>
        ///   A new object that is a copy of this instance.
        /// </returns>
        public object Clone()
        {
            object clone;
            using(MemoryStream stream = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, this);
                stream.Seek(0, SeekOrigin.Begin);
                clone = formatter.Deserialize(stream);
            }
            return clone;
        }

        #endregion

        public static YmlCatalog CreateYmlCatalogFromXml(IXPathNavigable doc)
        {
            XPathNavigator nav = doc.CreateNavigator();
            YmlCatalog catalog = new YmlCatalog();

            XPathNavigator catalogNode = nav.SelectSingleNode("//yml_catalog");
            if(catalogNode != null)
            {
                DateTime date;
                string strDate = catalogNode.GetAttribute("date", "");

                if(!string.IsNullOrEmpty(strDate)
                   &&
                   DateTime.TryParseExact(strDate,
                                          "yyyy-MM-dd HH:mm",
                                          CultureInfo.InvariantCulture,
                                          DateTimeStyles.None,
                                          out date))
                    catalog.Date = date;
                else
                    catalog.Date = DateTime.MinValue;
            }

            catalog.Shop = Shop.CreateShopFromXml(nav.SelectSingleNode("//yml_catalog/shop"));

            return catalog;
        }
    }
}